from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature
from flask import request, jsonify
from functools import wraps
from ..extensions import jys_db
import pymysql


# 获取token函数
def gen_token(user_id, expiration=1440 * 31 * 60):  # 单位为秒, 设定31天过期
    s = Serializer('123456', expires_in=expiration)
    return s.dumps({'id': user_id})  # user为model中封装过的对象


def token_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        token = request.cookies.get['token']
        s = Serializer('123456')
        try:
            data = s.loads(token)
        except SignatureExpired:
            return jsonify({'code': 0, 'data': '', 'msg': '过期的token'})
        except BadSignature:
            return jsonify({'code': 0, 'data': '', 'msg': '无效的token'})
        kwargs['user_id'] = data['id']
        return func(*args, **kwargs)

    return wrapper


def check_activate_token(token):
    # 生成serializer对象
    s = Serializer('123456')
    # 对解析token进行异常处理
    try:
        data = s.loads(token)
    except BadSignature:
        return jsonify({'code': 0, 'data': '', 'msg': '无效的token'})
    except SignatureExpired:
        return jsonify({'code': 0, 'data': '', 'msg': '过期的token'})
    # 从data中获取数据，即user.id
    # 根据获取到的user.id去查找用户
    id = data.get('id')
    sql = 'select * from bf_user where id=%d' % id
    user = jys_db.selectone(sql)
    # 判断用户是否存在
    if not user:
        return False
    else:
        return id
